package be.fedict.drupaltest.parts.installation;

import be.fedict.drupaltest.parts.BasePage;
import static be.fedict.drupaltest.parts.BasePage.getRadioElement;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

/**
 * Drupal installation wizard database page.
 * 
 * @author Bart Hanssens
 */
public class ChooseDatabasePage extends BasePage {
    @FindBy(id = "install-settings-form")
    private WebElement form;
    @FindBy(name = "driver")
    private List<WebElement> drivers;
    
    private WebElement database;
    private WebElement username;
    private WebElement password;
    private WebElement host;
    private WebElement port;
    private WebElement prefix;
    
     /**
     * Get a specific radio button (database) element.
     * 
     * @param driver database driver
     * @return element or null
     */
    public WebElement getDatabaseElement(String driver) {
        System.err.println("drivers : " + drivers.size());
        return getRadioElement(drivers, driver);
    }
    
    /**
     * Select the Drupal database
     * 
     * @param driver database driver
     */
    public void selectDatabase(String driver) {
        WebElement el = getDatabaseElement(driver);
        el.click();
      
        database = form.findElement(By.id("edit-" + driver + "-database"));
        username = form.findElement(By.id("edit-" + driver + "-username"));    
        password = form.findElement(By.id("edit-" + driver + "-password"));
        host = form.findElement(By.id("edit-" + driver + "-host"));
        port = form.findElement(By.id("edit-" + driver + "-port"));
        prefix = form.findElement(By.id("edit-" + driver + "-db-prefix"));
    }
    
    /**
     * Set the database info
     * 
     * @param name database name
     * @param user user name
     * @param password user password
     * @param dbHost database server
     */
    public void setDatabase(String name, String user, String pass, String dbHost) {
       database.clear();
       database.sendKeys(name);
       username.clear();
       username.sendKeys(user);
       password.clear();
       password.sendKeys(pass);
       
       if (! host.isDisplayed()) {
           form.findElement(By.tagName("a")).click();
       }
       host.clear();
       host.sendKeys(dbHost);
    }
    
    /**
     * Submit form
     */
    public void submit() {
        form.submit();
    }
}
